package com.module.retrofit;

import android.util.Log;

import com.module.netlib.BuildConfig;
import com.module.retrofit.coverter.JsonConverterFactory;
import com.module.retrofit.coverter.StringConverterFactory;
import com.module.retrofit.interceptor.CacheInterceptor;
import com.module.retrofit.interceptor.HearderInterceptor;
import com.module.retrofit.interceptor.ParameterInterceptor;
import com.module.retrofit.utils.logger.JsonUtil;
import com.module.retrofit.utils.logger.LogUtil;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by dell on 2017/2/16
 */

public class RetrofitClient {

    private long TIMEOUT_READ = 60;
    private long TIMEOUT_CONNECTION = 60;
    private final String Base_URL = "http://jisutqybmf.market.alicloudapi.com/weather/";
    private static RetrofitClient instance = new RetrofitClient();
    private Retrofit retrofit;
    private OkHttpClient mOkHttpClient;
    private CacheInterceptor mCacheInterceptor;

    private RetrofitClient() {
        createOkHttpClient();
        createRetrofit();
    }

    /**
     * 创建okhttp对象
     */
    private void createOkHttpClient() {
//        Map<String, String> headers = new LinkedHashMap<>();
//        headers.put("X-Foo", "Bar");
//        headers.put("X-Ping", "Pong");
//        headers.put("Authorization", "APPCODE 96360b38db304c759f4a7b481a2db69b");
        Map<String, String> parameters = new LinkedHashMap<>();
        parameters.put("param1", "param1");
        parameters.put("param2", "param2");

        /**创建okhttp对象*/
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        /**okhttp拦截器添加head 要在httpLoggingInterceptor之前*/
        builder.addInterceptor(new HearderInterceptor());
        /**okhttp拦截器添加parameters*/
        builder.addInterceptor(new ParameterInterceptor(parameters));

        /**必须是设置Cache目录*/
        Log.e("path", ApplicationHelper.getContext().getCacheDir().getAbsolutePath());
        builder.cache(new Cache(new File(ApplicationHelper.getContext().getCacheDir().getAbsolutePath(), "HttpCache"), 10 * 1024 * 1024));//缓存文件为10MB
         /**走缓存，两个都要设置*/
        mCacheInterceptor = new CacheInterceptor();
        builder.addInterceptor(mCacheInterceptor);
        builder.addNetworkInterceptor(mCacheInterceptor);

        /**失败重连*/
        builder.retryOnConnectionFailure(true);
        /**time out*/
        builder.readTimeout(TIMEOUT_READ, TimeUnit.SECONDS);
        builder.connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS);
        /**添加日志*/
        if (BuildConfig.DEBUG) {
            LogUtil.logInit(true);
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

                private StringBuilder mMessage = new StringBuilder();

                @Override
                public void log(String message) {
                    // 请求或者响应开始
                    if (message.startsWith("--> POST") || message.startsWith("--> GET")) {
                        mMessage.setLength(0);
                    }
                    // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
                    if ((message.startsWith("{") && message.endsWith("}"))
                            || (message.startsWith("[") && message.endsWith("]"))) {
                        message = JsonUtil.formatJson(JsonUtil.decodeUnicode(message));
                    }
                    mMessage.append(message.concat("\n"));
                    // 请求或者响应结束，打印整条日志
                    if (message.startsWith("<-- END HTTP")) {
                        LogUtil.d(mMessage.toString());
                    }
                }
            });
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }
        mOkHttpClient = builder.build();

    }

    /**
     * 创建retrofit对象
     */
    private void createRetrofit() {
        /**创建retrofit对象*/
        retrofit = new Retrofit.Builder()
                /**okhttp*/
                .client(mOkHttpClient)
                /**返回原始的的json —Call<String> 同StringConverterFactory*/
//                .addConverterFactory(StringConverterFactory.create())
//                /**返回对应类型 —Call<T>*/
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(JsonConverterFactory.create())
//                .addConverterFactory(StringConverterFactory.create())
                /**关联Rxjava —Observable<T>*/
//                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(Base_URL)
                .build();
    }

    public static RetrofitClient getInstance() {
        return instance;
    }

    public <T> T getApiService(Class<T> cls) {
        return retrofit.create(cls);
    }


    /**
     * 请求过渡类
     */
//    public static class RetrofitHelper {
//        public static void createC(Call mCall, Callback mCallback) {
//            mCall.enqueue(mCallback);
//        }
//
//        public <T> void createOS(Observable<T> mObservable, Consumer<T> mConsumer) {
//         /*http请求线程*/
//            mObservable.subscribeOn(Schedulers.io())
//                    .unsubscribeOn(Schedulers.io())
//                    /*回调线程*/
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(mConsumer);
//        }
//    }
}
